<template>
  <BasicModal @register="registerModal" @ok="handleAssignRole">
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { useModalInner, BasicModal } from '/@/components/Modal';
  import { useTable, BasicTable } from '/@/components/Table';
  import { roleColumns } from './data';
  import { getUserRole, assignRole } from '/@/api/sys/user';
  import { useMessage } from '/@/hooks/web/useMessage';

  const user_id = ref(0);
  const { createMessage } = useMessage();

  const emits = defineEmits(['register', 'success']);
  const [registerTable, { setTableData, reload, getSelectRowKeys, setSelectedRowKeys }] = useTable({
    columns: roleColumns,
    useSearchForm: false,
    showIndexColumn: false,
    canResize: false,
    rowKey: 'id',
    rowSelection: {},
    showTableSetting: true,
  });
  const [registerModal, { closeModal, setModalProps }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: true });
    user_id.value = data.record.id;
    let res = await getUserRole(user_id.value);
    let { roles, role_list } = res;
    setTableData(role_list);
    setSelectedRowKeys(roles);
    await reload();
    setModalProps({ confirmLoading: false });
  });

  async function handleAssignRole() {
    let roles = getSelectRowKeys();
    await assignRole(user_id.value, { roles });
    closeModal();
    emits('success');
    createMessage.success('角色分配成功');
  }
</script>

<style scoped></style>
